package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.HistoryRecordAdapter;
import com.dinadi.yidi.adapter.TotalDesignerAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.MessageBean;
import com.dinadi.yidi.bean.TotalDesignerRequest;
import com.dinadi.yidi.bean.TotalDesignerRequestEntity;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.KeybordS;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.pullloadmorerecyclerview.PullLoadMoreRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * author: JiaYu.He
 * Date: 2018/5/9   搜索设计师
 * Time: 11:15
 */
public class SearchDesignerActivity extends BaseActivity {
    private View view;
    private TextView cancel;
    private EditText edit_search;
    private ImageView clear_phone, img_no_comment, img_clear_history;
    private PullLoadMoreRecyclerView listView;
    private RelativeLayout layout_no_comment;
    private List<TotalDesignerRequestEntity> dataList = new ArrayList<>();
    private int page = 1;
    private TotalDesignerAdapter mRefreshAdapter;
    private PullLoadMoreRecyclerView mPullLoadMoreRecyclerView;
    /*是否显示没有的图片*/
    private boolean isShow = true;
    /*历史记录*/
    private LayoutInflater mInflater;
    private LinearLayout search_record;
    private List<String> mHistoryKeywords;
    private HistoryRecordAdapter mArrAdapter;
    private String userId, token;


    @Override
    protected View getLayout() {
        view = LayoutInflater.from(SearchDesignerActivity.this).inflate(R.layout.activity_search_product, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {

        changePager(2);
        cancel = (TextView) view.findViewById(R.id.cancel);
        edit_search = (EditText) view.findViewById(R.id.edit_search);
        clear_phone = (ImageView) view.findViewById(R.id.clear_phone);
//        layout_text = (LinearLayout) findViewById(R.id.layout_text);
        layout_no_comment = (RelativeLayout) view.findViewById(R.id.layout_no_comment);
        img_no_comment = (ImageView) view.findViewById(R.id.img_no_comment);
        mInflater = LayoutInflater.from(this);
        search_record = (LinearLayout) view.findViewById(R.id.search_record);
        img_clear_history = (ImageView) view.findViewById(R.id.img_clear_history);
        listView = (PullLoadMoreRecyclerView) view.findViewById(R.id.search_history_lv);
        listView.setLinearLayout();
        listView.setPushRefreshEnable(false);
        listView.setPullRefreshEnable(false);
        mHistoryKeywords = new ArrayList<String>();
        mArrAdapter = new HistoryRecordAdapter(SearchDesignerActivity.this);
        listView.setAdapter(mArrAdapter);


        mPullLoadMoreRecyclerView = (PullLoadMoreRecyclerView) view.findViewById(R.id.pullLoadMoreRecyclerView);
        mPullLoadMoreRecyclerView.setGridLayout(2);
        mRefreshAdapter = new TotalDesignerAdapter(SearchDesignerActivity.this);
        mPullLoadMoreRecyclerView.setAdapter(mRefreshAdapter);
        mPullLoadMoreRecyclerView.setOnPullLoadMoreListener(new PullLoadMoreListener());
        edit_search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0)
                    clear_phone.setVisibility(View.GONE);
                else
                    clear_phone.setVisibility(View.VISIBLE);
            }
        });

    }

    @Override
    protected void initListener() {

        registerClickListener(cancel, clear_phone, img_clear_history);
        edit_search.setOnEditorActionListener(editorActionListener);
        mArrAdapter.setmOnItemClickListener(new HistoryRecordAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String historyRecord) {
                edit_search.setText(historyRecord);
                initPullrefresh();
            }
        });
        mRefreshAdapter.setmOnItemClickListener(new TotalDesignerAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String data) {
                Intent intent = new Intent();
                intent.setClass(SearchDesignerActivity.this, DesignerHmePageActivity.class);
                intent.putExtra("dUserId", data);
                intent.putExtra("type", "2");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void initData() {
        userId = SharePreferencesHelper.getInstance(SearchDesignerActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(SearchDesignerActivity.this).getString("token");
        initSearchHistory();

    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {

            case R.id.cancel:
                SearchDesignerActivity.this.finish();
                break;
            case R.id.clear_phone:
                edit_search.setText("");
                break;
            case R.id.img_clear_history:
                cleanHistory();
                break;
            default:
                break;

        }

    }

    private final EditText.OnEditorActionListener editorActionListener =
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == KeyEvent.ACTION_DOWN || actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO) {
                        mRefreshAdapter.clearData();
                        save();
                        showLoadingDialog("");
                        initPullrefresh();

                        KeybordS.closeKeybord(edit_search, SearchDesignerActivity.this);
                    }
                    return true;
                }
            };

    private void initPullrefresh() {

        MessageBean bean = new MessageBean();
        bean.setToken(token);
        bean.setUserId(userId);
        bean.setPageNum(page + "");
        bean.setPageSize("10");
        bean.setUserName(edit_search.getText().toString());
//        bean.setType("2");
        CommonInterface messageInterface = new CommonInterface(SearchDesignerActivity.this, httpListener);
        messageInterface.getInterface("13001", JSON.toJSONString(bean));

    }


    public void initSearchHistory() {

        String history = SharePreferencesHelper.getInstance(SearchDesignerActivity.this).getString("designerHistoryRecord");
        if (!TextUtils.isEmpty(history)) {
            List<String> list = new ArrayList<String>();
            for (Object o : history.split(",")) {
                list.add((String) o);
            }
//            mHistoryKeywords = list;
            mArrAdapter.addAllData(list);
        }
    }

    /*保存历史记录*/
    public void save() {
        String text = edit_search.getText().toString();
        String oldText = SharePreferencesHelper.getInstance(SearchDesignerActivity.this).getString("designerHistoryRecord");
        if (!TextUtils.isEmpty(text) && !oldText.contains(text)) {
            SharePreferencesHelper.getInstance(SearchDesignerActivity.this).putString("designerHistoryRecord", text + "," + oldText);
            mHistoryKeywords.add(0, text);
        }
        mArrAdapter.notifyDataSetChanged();
    }

    /*清除历史记录*/
    public void cleanHistory() {
        SharePreferencesHelper.getInstance(SearchDesignerActivity.this).removeString("designerHistoryRecord");
        mArrAdapter.clearData();
        ToastUtil.showToast("清除成功");

    }

    private void getData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                //刷新结束
                mPullLoadMoreRecyclerView.setPullLoadMoreCompleted();
            }
        }, 1000);
    }


    class PullLoadMoreListener implements PullLoadMoreRecyclerView.PullLoadMoreListener {
        @Override
        public void onRefresh() {
            setRefresh();
        }

        @Override
        public void onLoadMore() {
            page = page + 1;
            isShow = false;
            initPullrefresh();
        }
    }

    private void setRefresh() {
        mRefreshAdapter.clearData();
        page = 1;
        initPullrefresh();
    }

    HttpListener httpListener = new HttpListener() {

        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            search_record.setVisibility(View.GONE);
            mPullLoadMoreRecyclerView.setVisibility(View.VISIBLE);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                TotalDesignerRequest bean = JsonUtil.parseJsonToBean(response, TotalDesignerRequest.class);
                dataList = bean.getDesignerList();
                if (dataList.size() == 0) {
                    if (isShow == false) {
                        layout_no_comment.setVisibility(View.GONE);
                    } else {
                        layout_no_comment.setVisibility(View.VISIBLE);
                        img_no_comment.setImageResource(R.drawable.img_no_search);
                    }
                } else {
                    layout_no_comment.setVisibility(View.GONE);
                }
                mRefreshAdapter.addAllData(dataList);
//                if (page == 1) {
//                    if (dataList.size() == 0) {
//                        text_prompt.setVisibility(View.VISIBLE);
//                    } else {
//                        text_prompt.setVisibility(View.GONE);
//
//                    }
//                } else {
//                    text_prompt.setVisibility(View.GONE);
//
//                }

                getData();
            } else {
                closeLoadingDialog();
                toast(errMsg);
            }


        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            toast("加载失败");
        }
    };
}
